<template>
  <div class="charge">
    <div class="w1200">
      <UserInfo />
      <div class="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="c-01">
              <div class="icon">
                <span>{{ $t("自定义充值金额：") }}</span>
              </div>
            </div>
            <div class="c-02 pt20">
              <el-form ref="from" :model="form" :rules="rules" style="flex: 1">
                <el-form-item prop="amount">
                  <el-input :placeholder="$t('请输入充值金额')" v-model="form.amount" type="number"></el-input>
                </el-form-item>
              </el-form>

              <el-button class="btn" type="primary" @click="submit">{{
                $t("确认充值")
                }}</el-button>
            </div>
            <div class="c-03 pt20">
              <div :class="['i', item === form.amount ? 'active' : '']" v-for="item in amountAvails" :key="item"
                @click="form.amount = item">
                {{ item }}元
              </div>
            </div>
            <div class="c-04 pt20">
              {{ $t("大额充值联系管理员")
              }}<span class="red">{{ $t("免手续费") }}</span>
            </div>
            <div class="c-05">
              <el-radio-group v-model="radio" style="display: flex; flex-wrap: nowrap">
                <el-radio style="width: 50%; display: flex; align-items: center" name="aliPay" value="0"
                  inputid="aliPay" :label="0">
                  <img class="ico" src="@/assets/images/pay_icon_05.png" alt="" />
                  <label for="aliPay" class="mr-3 ng-star-inserted">{{ $t("支付宝支付") }}
                    <span style="color: red" class="ng-star-inserted">(1% {{ $t("手续费") }})</span>
                  </label>
                </el-radio>
                <el-radio style="width: 50%; display: flex; align-items: center" name="weChatPay" inputid="weChatPay"
                  value="1" :label="1">
                  <img class="ico" src="@/assets/images/pay_icon_03.png" alt="" />
                  <label for="weChatPay" class="mr-3 ng-star-inserted">{{ $t("微信支付") }}
                    <span style="color: red" class="ng-star-inserted">(1% {{ $t("手续费") }})</span>
                  </label>
                </el-radio>
              </el-radio-group>
            </div>
            <div class="c-06">
              <div class="icon">
                <span>{{ $t("温馨提醒") }}</span>
              </div>
            </div>
            <div class="c-07 pt20">
              <div class="t t1">
                {{ $t("1，积分提现需要余额大于或等于10元，低于10元无法提现") }}
              </div>
              <div class="t t1">
                {{ $t("2，积分提现需要支付1%的手续费费用") }}
              </div>
              <div class="t t1">
                {{ $t("3，充值金额≥200可以联系客服充值免除手续费，提现也可以免除手续费")
                }}
              </div>
              <div class="t t1">
                {{ $t("4，如果需要提现，公众号聊天框输入:“提现”，然后点击发送，如果提现遇到问题请联系 {客服微信}") }}
              </div>
              <div class="t t1">
                {{ $t("5，累计充值的金额越多，会员等级越高，大客户可联系网站管理员增加积分") }}
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="search-form">
              <div class="c-08">
                <div class="icon">
                  <span>{{ $t("筛选账单") }}</span>
                </div>
              </div>
              <el-form :model="formSelect" ref="ref" :rules="rulse">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item :label="$t('账单ID') + '（' + $t('可选') + '）'" prop="id">
                      <el-input :placeholder="$t('输入账单ID')" v-model="formSelect.id"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="$t('充值金额') + '（' + $t('可选') + '）'" prop="payAmount">
                      <el-input :placeholder="$t('充值金额')" v-model="formSelect.payAmount"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="$t('充值结果')" prop="payResult">
                      <el-select :placeholder="$t('选择状态')" style="width: 100%" v-model="formSelect.payResult">
                        <el-option :label="$t('成功')" value="1"></el-option>
                        <el-option :label="$t('失败')" value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="$t('排序')" prop="orderByKey">
                      <el-select :placeholder="$t('选择排序类型')" style="width: 100%" v-model="formSelect.orderByKey">
                        <el-option v-for="(_, key) in orderByMap" :key="key" :label="key" :value="key" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="$t('支付方式') + '（' + $t('可选') + '）'" prop="payWay">
                      <el-select :placeholder="$t('选择支付方式')" style="width: 100%" v-model="formSelect.payWay">
                        <el-option :label="$t('微信')" value="ALI_QR"></el-option>
                        <el-option :label="$t('支付宝')" value="WX_QR"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="$t('交易号') + '（' + $t('可选') + '）'" prop="payNum">
                      <el-input :placeholder="$t('输入交易号')" v-model="formSelect.payNum"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item :label="$t('创建时间') + '（' + $t('可选') + '）'" prop="createTime">
                      <el-date-picker v-model="formSelect.createTime" type="datetimerange" align="right"
                        :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')"
                        :default-time="['12:00:00', '08:00:00']" style="width: 100%">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="op-bts" style="margin-top: 10px">
        <el-button size="medium" @click="searchByPcForm">{{
          $t("筛选")
          }}</el-button>
        <el-button size="medium" @click="countByPcForm">{{
          $t("计数")
          }}</el-button>
        <el-button size="medium" @click="resetFrom">{{ $t("重置") }}</el-button>
      </div>
      <div class="block" style="padding: 10px 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50, 200]" :page-size="pageSize" :total="total"
          layout="prev, pager, next, jumper, sizes" style="text-align: center">
          <span>{{ currentPage }}</span>
        </el-pagination>
      </div>
      <div style="padding-bottom: 20px">
        <el-table @selection-change="handleSelectionChange" :data="orderList" stripe style="width: 100%">
          <el-table-column prop="payNum" :label="$t('订单Id')"></el-table-column>
          <el-table-column :label="$t('充值方式')">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.payWay == 'ALI_QR'">{{
                $t("支付宝")
                }}</el-tag>
              <el-tag type="success" v-else>{{ $t("微信") }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="payAmount" :label="$t('充值金额')"></el-table-column>
          <el-table-column :label="$t('充值结果')">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.payResult == 1">{{
                $t("成功")
                }}</el-tag>
              <el-tag type="danger" v-else>{{ $t("失败") }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :label="$t('创建时间')"
            :formatter="(_row, _, val) => formatDateTime(new Date(val))" />
        </el-table>
      </div>
    </div>
    <pay-modal ref="payModal" :visible="visible" :result="apiRes" @closeDialog="closeDialog"></pay-modal>
  </div>
</template>

<script>
import UserInfo from "@/components/home/UserInfo.vue";
import apiService from "@/api/apiService";
import PayModal from "./PayModal";
import { formatDateTime } from "@/utils";
import Vue from "vue";

export default {
  name: "ReCharge",
  components: { PayModal, UserInfo },
  data() {
    return {
      formatDateTime,
      visible: false,
      amountAvails: [1, 5, 10, 30, 50, 100, 200],
      radio: 0,
      agreeCheck: false,
      form: {
        amount: '',
      },
      formSelect: {
        id: '',
        payAmount: '',
        payResult: '',
        payWay: '',
        payNum: '',
        createTime: '',
        orderByKey: ''
      },
      rulse: {},
      apiRes: {}, // 接口返回数据包
      // keyboard: "",
      // payMethod: "wx",
      // wxpaySvgSrc: require("@/assets/wxpay.svg"),
      // aliPaySvgSrc: require("@/assets/alipay.svg"),
      rules: {
        amount: [
          { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: this.validateAmount, trigger: "blur" },
        ],
      },
      user: null,
      orderList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    amount(amount) {
      if (amount < 1) {
        this.$message({
          msg: "最低可充值1元",
          duration: 3000,
        });
        this.amount = 1;
      }
    },
  },
  computed: {
    orderByMap() {
      let orderByMap = {};
      let orderFields = [
        {
          field: "create_time",
          cname: "创建时间",
        },
        {
          field: "update_time",
          cname: "更新时间",
        },
        {
          field: "price",
          cname: "订单金额",
        },
      ];
      let orderBys = [
        {
          order: "desc",
          cname: "降序",
        },
        {
          order: "asc",
          cname: "升序",
        },
      ];
      orderFields.forEach((f) => {
        orderBys.forEach((b) => {
          orderByMap[f.cname + b.cname] = {
            orderFiled: f.field,
            orderBy: b.order,
          };
        });
      });
      return orderByMap;
    },
  },
  methods: {
    closeDialog(val) {
      this.visible = val;
    },
    submit() {
      this.$refs.from.validate((valid) => {
        if (!valid) {
          return false;
        }
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        // if (this.agreeCheck) {
        // eslint-disable-next-line no-constant-condition
        if (true) {
          const params = {
            wayCode: "",
            amount: this.form.amount,
            payDataType: "",
          };

          // if (isMobile()) {
          //   //手机端
          //   if (this.radio === 0) {
          //     params.wayCode = "ALI_QR";
          //     params.payDataType = "payUrl";
          //   }
          //   //TODO 后面需要调起微信支付
          //   if (this.radio === 1) {
          //     params.wayCode = "WX_JSAPI";
          //     params.payDataType = "codeUrl";
          //   }
          // } else {
            //PC端
            if (this.radio === 0) {
              params.wayCode = "ALI_QR";
              params.payDataType = "codeImgUrl";
            }
            if (this.radio === 1) {
              params.wayCode = "WX_NATIVE";
              params.payDataType = "codeImgUrl";
            }
          // }
          apiService
            .post("/rechange", params)
            .then((res) => {
              this.visible = true;
              this.apiRes = res.data;
              this.$refs.payModal.showModal(params.wayCode, res.data); // 打开弹窗
              loading.close();
            })
            .catch(() => {
              Vue.prototype.$message.error("服务器异常,请重试");
              loading.close();
            });
        }
      });
    },
    validateAmount(rule, value, callback) {
      value = `${value}`.trim();
      let n = Number(value);
      if (isNaN(n)) {
        return callback(new Error("请输入数字"));
      }

      if (n === 0) {
        return callback();
      }

      // 可见小数位
      let { message } = rule;
      const reg = new RegExp(`^[1-9]\\d*$`);
      if (value && !reg.test(value)) {
        callback(new Error(message || "只允许输入正整数"));
      } else {
        return callback();
      }
    },
    searchByPcForm() {
      this.getList();
    },
    countByPcForm() {
      let pageCount = Math.ceil(this.total / this.pageSize);
      this.$notify({
        title: "计数完成",
        message: `共${this.total}个订单符合筛选条件，${pageCount}页`,
        type: "success",
        position: "bottom-right",
      });
    },
    resetFrom() {
      Object.keys(this.formSelect).forEach(key => {
        this.formSelect[key] = ''
      })
    },
    handleSelectionChange() { },
    getList() {
      const parems = {
        createdStart: this.formSelect.createTime?.[0],
        createdEnd: this.formSelect.createTime?.[1],
        orderFiled: this.orderByMap[this.formSelect.orderByKey]?.orderFiled,
        orderBy: this.orderByMap[this.formSelect.orderByKey]?.orderBy,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        ...this.formSelect
      };
      apiService
        .post("/paylog-list", parems)
        .then((res) => {
          this.orderList = res.data.records;
          this.total = res.data.total;
        });
    },
    /* 页大小变了依旧用之前的请求, 从第一页开始查 */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    //     changeAmount(val) {
    //       console.log(this.amount);
    //       console.log(val);
    //     },
    //     pay() {
    //       if (this.payMethod === "wx") {
    //         this.$toast.loading({
    //           loadingType: "ring",
    //           loadingColor: "green",
    //           msg: "支付中...",
    //         });
    //         setTimeout(() => {
    //           this.$toast.close();
    //         }, 3000);
    //       } else {
    //         this.$toast.loading({
    //           loadingType: "ring",
    //           msg: "支付中...",
    //         });
    //         setTimeout(() => {
    //           this.$toast.close();
    //         }, 3000);
    //       }
    //     },
  },
};
</script>

<style lang="scss" scoped>
.top {
  padding-top: 20px;

  .search-form {
    background-color: #f6f9fe;
    padding: 10px;
  }

  .c-08 {
    width: 120px;
    margin-bottom: 10px;

    .icon {
      span {
        padding-left: 10px;
      }
    }
  }

  .c-07 {
    .t1 {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;

      span {
        font-size: 16px;
      }
    }

    .t2 {
      font-size: 16px;
      color: red;
    }
  }

  .c-06 {
    width: 120px;

    .icon {
      span {
        padding-left: 10px;
      }
    }
  }

  .c-05 {
    padding: 20px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    margin: 20px 0;

    .ico {
      margin-right: 5px;
    }
  }

  .c-04 {
    color: #666;
    font-size: 16px;
  }

  .c-03 {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .i {
      cursor: pointer;
      height: 32px;
      color: #333;
      padding: 0 15px;
      display: flex;
      justify-content: center;
      border: 1px solid #ccc;
      border-radius: 8px;
      align-items: center;

      &.active {
        color: #fff;
        background-image: linear-gradient(to right, #7594fc, #4584fd);
      }
    }
  }

  .c-02 {
    display: flex;

    .btn {
      width: 120px;
      flex-shrink: 0;
      margin-left: 20px;
      background-color: #ffae00;
      border: none;
    }
  }

  .c-01 {
    width: 160px;

    .icon {
      span {
        padding-left: 10px;
      }
    }
  }
}

.op-bts {
  display: flex;
  flex-wrap: wrap;
  padding-top: 20px;
  border-bottom: 2px solid #f2f2f2;
  padding-bottom: 6px;
}

.op-bts .el-button {
  color: #0d9db0;
  margin-top: 0.5rem;
}

.red {
  color: #ff0000;
}

.pt20 {
  padding-top: 20px;
}

.icon {
  height: 40px;
  background-image: url("@/assets/images/icon_01_03.jpg");
  background-repeat: no-repeat;
  background-position: left;
  background-size: auto 40px;
  padding-left: 30px;
  opacity: 0.8;

  span {
    color: #fff;
    background-color: #5288e8;
    display: block;
    font-size: 14px;
    border-radius: 0 10px 10px 0;
    display: block;
    height: 40px;
    line-height: 40px;
  }
}

::v-deep .c-05 .el-radio__label {
  display: flex;
  align-items: center;
}

.pay-panel {
  box-shadow: 0 0 0 0.2rem #00000005;
  border-radius: 10px;
  border: solid white 1px;
  background: rgb(255, 255, 255);
  margin: auto;
  width: 95%;
}

.shadow-2 {
  margin: auto;
  width: 90%;
  padding: 20px 20px 20px 20px;
}

.text-c-101 {
  width: 100%;
  text-align: left;
  font-weight: bolder;
  margin-bottom: 10px;
}

.text-c-102 {
  width: 100%;
  text-align: left;
  font-weight: bolder;
  margin-bottom: 2px;
}

::v-deep .c-02 .el-form-item {
  margin-bottom: 0;
}
</style>
